// Copyright (c) Appeon
// The following has been modified by Appeon under compliance with the Apache 2.0 license from the original work

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System.Data;
using System.Data.Common;
using JetBrains.Annotations;
using Microsoft.Data.SqlClient;

namespace SnapObjects.Data.SqlServer
{
    public class SqlServerDateTimeTypeMapping : DateTimeTypeMapping
    {
        private const string DateTimeFormatConst = "{0:yyyy-MM-dd HH:mm:ss.fff}";
        private const string DateTime2FormatConst = "{0:yyyy-MM-dd HH:mm:ss.FFFFFFF}";

        /// <summary>
        ///     Initializes a new instance of the <see cref="SqlServerDateTimeTypeMapping" /> class.
        /// </summary>
        /// <param name="dbTypeName"> The name of the database type. </param>
        /// <param name="dbType"> The <see cref="System.Data.DbType" /> to be used. </param>
        public SqlServerDateTimeTypeMapping(
            [NotNull] string dbTypeName,
            [CanBeNull] DbType? dbType = null)
            : base(dbTypeName, dbType)
        {
        }

        protected override void ConfigureParameter(DbParameter parameter, IAdoDbParameter adoDbParameter)
        {
            base.ConfigureParameter(parameter, adoDbParameter);

            // Workaround for a SQLClient bug
            if (this.DbType == System.Data.DbType.Date)
            {
                ((SqlParameter)parameter).SqlDbType = SqlDbType.Date;
            }
        }

        /// <summary>
        ///     Creates a copy of this mapping.
        /// </summary>
        /// <param name="dbTypeName"> The name of the database type. </param>
        /// <param name="size"> The size of data the property is configured to store, or null if no size is configured. </param>
        /// <returns> The newly created mapping. </returns>
        public override TypeMapping Clone(string dbTypeName, int? size)
        {
            return new SqlServerDateTimeTypeMapping(dbTypeName, this.DbType);
        }

        /// <summary>
        ///     Gets the string format to be used to generate SQL literals of this type.
        /// </summary>
        protected override string SqlLiteralFormatString
        {
            get
            {
                if (this.DbTypeName.Equals("datetime2"))
                {
                    return "'" + DateTime2FormatConst + "'";
                }
                else
                {
                    return "'" + DateTimeFormatConst + "'";
                }
            }
        }
    }
}
